package org.tony.service;


import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.directwebremoting.annotations.RemoteMethod;
import org.directwebremoting.annotations.RemoteProxy;
import org.tony.db.DbUtil;
import org.tony.entity.DataCusomizedEntry;
import org.tony.entity.DbEntry;
import org.tony.entity.RelationDataSourceEntry;
import org.tony.utils.DataCustomizedUtil;
import org.tony.utils.JdbcHelper;
import org.tony.utils.XmlDataSourceHelper;

import com.alibaba.fastjson.JSON;

/**
 * 系统服务类，供前端调用
 * @author tony
 *
 */
@RemoteProxy
public class SystemService {
	
	
	/**
	 * 获取所有数据源
	 * @return
	 */
	@RemoteMethod
	public Object getDataSources() {
		Collection<DbEntry> entries = XmlDataSourceHelper.getInstance().getDbEntryList() ;
		return JSON.toJSON(entries) ;
	}
	
	/**
	 * 根据id获取所有表
	 * @param id
	 * @return
	 */
	@RemoteMethod
	public Object getTablesByDsId(String id) {
		DbEntry entry = XmlDataSourceHelper.getInstance().findDbEntryById(id);
		List<String> allTales =null ;
		if(entry!=null) {
			allTales = DbUtil.getAllTables(entry);
		}
		return allTales ;
	}
	
	/**
	 * 获取系统数据库中的表
	 * @return
	 */
	@RemoteMethod
	public Object getSystemTables() {
		List<String> allTales =null ;
		allTales = DbUtil.getAllTables(JdbcHelper.system);
		return allTales ;
	}
	
	/**
	 * 获取指定表的 列
	 * @param tableName
	 * @return
	 */
	@RemoteMethod
	public Object getColumnsByTableName(String tableName) {
		if(tableName==null) {
			return null;
		}
		return DbUtil.getTableColumns(tableName, JdbcHelper.system,true);
	}
	
	/**
	 * 获取指定表的所有列
	 * @param tableName
	 * @param dsId
	 * @return
	 */
	@RemoteMethod
	public Object getAllColumsByTableName(String tableName,String dsId) {
		Map<String,String> res = DbUtil.getTableColumns(tableName, XmlDataSourceHelper.getInstance().findDbEntryById(dsId),false);
		return res ;
	}
	
	/**
	 * 生成定制数据模板
	 * @param jsonStr
	 * @return
	 */
	@RemoteMethod
	public String submitCustomized(String jsonStr) {
		try{
			DataCusomizedEntry d = JSON.parseObject(jsonStr, DataCusomizedEntry.class);
			d.setRelationId(org.tony.utils.IdGenerator.generateId());
			d.trim() ;
			if(d.getRelDts().size()>0) {
				DataCustomizedUtil.getInstance().writeRelation(d);
				List<RelationDataSourceEntry> rels = d.getRelDts() ;
				for(RelationDataSourceEntry rel:rels) {
					String dsId = rel.getFromDateSourceId();
					String tableName = rel.getFromTableName();
					Map<String,String> columns = rel.getColumns() ;
					if(columns!=null && dsId!=null && tableName!=null && columns.size()>0) {
						boolean bool = DbUtil.createTrigger(tableName,columns , XmlDataSourceHelper.getInstance().findDbEntryById(dsId),d.getRelationId(),rel.getRelationKey());
						if(bool) {
							return "success:数据定制成功";
						}else {
							return "failure:系统出现故障";
						}
					}
				}
				return "failure:数据定制失败，请检查选择项是否有问题？" ;
			}else{
				return "failure:系统已经存在相应列的数据定制" ;
			}
		}catch (Exception e) {
			e.printStackTrace();
			return "failure:数据定制失败";
		}
	}
	
	/**
	 * 注册数据源
	 * @param jsonStr
	 * @return
	 */
	@RemoteMethod
	public String registDataSource(String jsonStr) {
		try{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			System.out.println(jsonStr);
			DbEntry entry = JSON.parseObject(jsonStr,DbEntry.class) ;
			if(entry != null) {
				entry.setDriverClass(JdbcHelper.driverClasses.get(entry.getDatabaseType().trim())) ;
				entry.setId(entry.getDataSourceIp()+"_" + entry.getPort() + "_"+entry.getDatabaseType()) ;
				entry.setRegDate(sdf.format(new Date())) ;
				boolean bool = XmlDataSourceHelper.getInstance().writeXmlEntry(entry);
				if( bool ) {
					return "数据源注册成功";
				}
			}
		}catch (Exception e) {
			e.printStackTrace() ;
		}
		return "数据源注册失败" ;
	}
	
	/**
	 * 测试数据源连接
	 * @param id
	 * @return
	 */
	@RemoteMethod
	public String testConnection(String id) {
		try{
			boolean result = JdbcHelper.testConnection(XmlDataSourceHelper.getInstance().findDbEntryById(id));
			return String.valueOf(result) ;
		}catch (Exception e) {
			return "false";
		}
	}
	
	/**
	 * 删除数据源
	 * @param ids
	 * @return
	 */
	@RemoteMethod
	public String deleteById(String[] ids) {
		StringBuffer res = new StringBuffer("{") ;
		boolean bool = false ;
		for(String id:ids) {
			try{
				bool = 	XmlDataSourceHelper.getInstance().deleteXmlEntry(id);
				if(!bool) {
					res.append(id+",") ;
				}
			}catch (Exception e) {
				bool = false ;
				res.append(id+",") ;
			}
		}
		res.append("} 删除失败");
		if(bool) {
			return "删除成功" ;
		}else {
			return res.toString() ;
		}
	}
	
	/**
	 * 查找数据源
	 * @param id
	 * @return
	 */
	@RemoteMethod
	public Object findByDsId(String id) {
		return JSON.toJSON(XmlDataSourceHelper.getInstance().findDbEntryById(id)) ;
	}
	
	/**
	 * 修改数据源
	 * @param jsonStr
	 * @return
	 */
	@RemoteMethod
	public String modifyDs(String jsonStr ){
		try{
			DbEntry entry = JSON.parseObject(jsonStr,DbEntry.class) ;
			if(entry!=null) {
				entry.setDriverClass(JdbcHelper.driverClasses.get(entry.getDatabaseType())) ;
				XmlDataSourceHelper.getInstance().deleteXmlEntry(entry.getId()) ;
				XmlDataSourceHelper.getInstance().writeXmlEntry(entry);
				
				return "true:数据修改成功";
			}
		}catch (Exception e) {
		}
		
		return "false:数据修改失败" ;
	}
}
